CREATE FUNCTION dbo.CountLayer
(
    @node_id int
)
RETURNS int
AS
begin
    declare @result int
    set @result = 0
    declare @lft int
    declare @rgt int
    if exists(select Node_id from Tree where Node_id = @node_id)
    begin
        select @lft = Lft, @rgt = Rgt from Tree where node_id = @node_id
        select @result = count(*) from Tree where Lft <= @lft and Rgt >= @rgt
    end
    return @result
end
GO